﻿using MQTTnet;
using MQTTnet.Client;
using System.Text;

namespace MqttClient1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 创建MQTT客户端
            var mqttClient = new MqttFactory().CreateMqttClient();

            // 配置MQTT客户端选项
            var options = new MqttClientOptionsBuilder()
                //.WithTcpServer("broker.emqx.io", 1883) // MQTT Broker地址和端口
                .WithTcpServer("127.0.0.1", 1883) // MQTT Broker地址和端口
                .WithClientId("0667767D61514BCCB6EF9C504B5256B1") // 客户端ID
                .Build();

            // 连接到MQTT Broker
            await mqttClient.ConnectAsync(options);
            Console.WriteLine("Connected to MQTT Broker");

            // 订阅主题
            await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("0667767D61514BCCB6EF9C504B5256B/topic").Build());
            Console.WriteLine("Subscribed to topic: 0667767D61514BCCB6EF9C504B5256B/topic");

            // 处理接收到的消息
            mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;

            // 发布消息
            var message = new MqttApplicationMessageBuilder()
                .WithTopic("0667767D61514BCCB6EF9C504B5256B/topic")
                .WithPayload("MqttClient1 MQTT from C#")
                .Build();

            await mqttClient.PublishAsync(message);
            Console.WriteLine("Message published");

            // 保持程序运行以便接收消息
            Console.ReadLine();

            // 断开连接
            await mqttClient.DisconnectAsync();
            Console.WriteLine("Disconnected from MQTT Broker");
        }

        private static Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            Console.WriteLine("Received message:");
            Console.WriteLine($"Topic: {e.ApplicationMessage.Topic}");
            Console.WriteLine($"Payload: {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
            return Task.CompletedTask;
        }
    }
}
